package cate.game.train.fairy;

import cate.common.table.d.GDObj;
import cate.common.table.d.GDOperation;
import cate.common.table.item.fairy.row.FairyBaseRow;
import cate.common.util.GameResult;
import cate.game.client.msg.MergeMsgSender;
import cate.game.event.RoleEventPublisher;
import cate.game.event.hero.HeroPowerChangeEvent;
import cate.game.res.CostSelect;
import cate.game.res.MixRes;
import cate.game.res.MixResItem;
import cate.game.res.RewardShow;
import cate.game.role.Role;
import cate.game.role.bag.fairy.Fairy;
import cate.game.role.bag.hero.Hero;
import cate.game.train.fairy.msg.FairyLevelUpResp;
import cate.game.train.fairy.msg.FairyOffResp;
import easy.java.dev.note.NoteClass;
import easy.java.practice.errorcode.EcResult;
import org.apache.commons.lang3.StringUtils;

import java.util.List;


@NoteClass(value = "灵器处理")
public class TrainFairyHandler implements RoleEventPublisher {

    public GameResult<Void> levelUp(
            Role role, String fairyUid, String heroUid, byte pos, CostSelect cs) {
        GameResult<Void> r = new GameResult<>();
        Fairy fairy = getFairy(role, fairyUid, heroUid, pos);
        if (fairy == null) {
            return r.fail("灵器不存在");
        }
        FairyBaseRow row = fairy.getTpl(role.getGame().fight.getPlayBuildContext());
        if (row == null) {
            return r.fail("灵器配置有误");
        }
        if (StringUtils.isBlank(row.levelUpCost1) && StringUtils.isBlank(row.levelUpCost2)) {
            return r.fail("灵器已满级");
        }
        MixRes levelUpConsume = new MixRes(row.levelUpCost2);
        EcResult<MixResItem> itemConsumeRes = levelUpConsume.consumeCheck(role, null);
        if (!itemConsumeRes.ok()) {
            role.getGame().notice.tipResItem(role, itemConsumeRes.data);
            return r.fail(itemConsumeRes.message);
        }
        if (StringUtils.isNotBlank(row.levelUpCost1)) {
            EcResult<MixResItem> fairyConsumeRes = new MixRes(row.levelUpCost1).consume(role, cs);
            if (!fairyConsumeRes.ok()) {
                role.getGame().notice.tipResItem(role, fairyConsumeRes.data);
                return r.fail(fairyConsumeRes.message);
            }
        }
        levelUpConsume.consumeDirect(role, null);
        fairy.tid = row.nextTid;
        role.sendNow(new FairyLevelUpResp(fairy, heroUid, pos));

        if (StringUtils.isNotBlank(heroUid)) {
            role.getBase().updatePower();
            publishEvent(role, new HeroPowerChangeEvent(role,  getHero(role, heroUid)));
        }
        role.getGame().notice.message(role, "升级成功");
        return r.success();
    }

    public GameResult<Void> back(Role role, String fairyUid, String heroUid, byte pos) {
        GameResult<Void> r = new GameResult<>();
        Fairy fairy = getFairy(role, fairyUid, heroUid, pos);
        if (fairy == null) {
            return r.fail("灵器不存在");
        }
        FairyBaseRow row = fairy.getTpl(role.getGame());
        if (row == null) {
            return r.fail("灵器配置有误");
        }
        MixRes backReward = new MixRes(row.backRwdStr);
        if (backReward.isEmpty()) {
            return r.fail("该灵器无法回炉");
        }
        row = role.getGame().table.fairy.base.getRow(row.protoId, 0);
        if (row == null) {
            return r.fail("该灵器无法回炉");
        }
        EcResult<MixResItem> consumeRes = new MixRes(row.backCostStr).consume(role, null);
        if (!consumeRes.ok()) {
            role.getGame().notice.tipResItem(role, consumeRes.data);
            return r.fail(consumeRes);
        }
        fairy.tid = row.id;
        role.sendNow(new FairyLevelUpResp(fairy, heroUid, pos));

        backReward.add(role, true, GDOperation.FAIRY_BACK);
        RewardShow rewardShow = new RewardShow();
        rewardShow.addTplRwd(backReward);
        role.getGame().notice.dialog(role, rewardShow);

        if (StringUtils.isNotBlank(heroUid)) {
            Hero hero = getHero(role, heroUid);
            role.getBase().updatePower();
            publishEvent(role, new HeroPowerChangeEvent(role, hero));
        }
        role.getGame().notice.message(role, "回炉成功");
        return r.success();
    }

    public GameResult<Void> decomposed(Role role, List<String> fairyUids) {
        GameResult<Void> r = new GameResult<>();
        if(fairyUids == null || fairyUids.isEmpty()){
            return r.fail("灵器不可为空");
        }
        MixRes reward = new MixRes();
        MergeMsgSender sender = new MergeMsgSender();
        for(String fairyUid : fairyUids){
            Fairy fairy = role.getBag().getFairy().getItem(fairyUid);
            if (fairy == null) {
                role.getGame().notice.message(role, "灵器不存在");
                continue;
            }
            FairyBaseRow fairyBaseRow = fairy.getTpl(role.getGame());
            if (fairyBaseRow == null) {
                role.getGame().notice.message(role, "灵器不存在");
                continue;
            }
            MixRes treward = new MixRes();
            List<FairyBaseRow> rows = role.getGame().table.fairy.base.getLevelLowerRows(fairyBaseRow.protoId, fairyBaseRow.level);
            if (!rows.isEmpty()) {
                for (FairyBaseRow row : rows) {
                    if (StringUtils.isNotBlank(row.returnStr)) {
                        treward.addList(new MixRes(row.returnStr));
                    }
                    if (row.level > 0 && StringUtils.isNotBlank(row.levelUpCost1)) {
                        treward.addList(new MixRes(row.levelUpCost1));
                    }
                    if (row.level > 0 && StringUtils.isNotBlank(row.levelUpCost2)) {
                        treward.addList(new MixRes(row.levelUpCost2));
                    }
                }
            }
            r = treward.addCheck(role);
            if (!r.ok()) {
                role.getGame().notice.message(role, r.message);
                continue;
            }
            GameResult<RewardShow> removeRes = role.getBag().getFairy().removeItem(fairyUid, sender);
            // 发奖励
            if (!removeRes.ok()) {
                role.getGame().notice.message(role, removeRes.message);
                continue;
            }
            reward.addList(treward);
        }
        sender.send(role, true);
        reward.add(role,true,GDOperation.FAIRY_DECOMPOSE);
        role.getGame().notice.dialogReward(role, reward);
        return r;
    }

    public GameResult<Void> compose(Role role, int tid) {
        GameResult<Void> r = new GameResult<>();
        FairyBaseRow row = role.getGame().table.fairy.base.get(tid);
        if (row == null) {
            return r.fail("灵器不存在");
        }
        if (role.getBag().getFairy().gridEmpty() < 1) {
            return r.fail("背包容量不足");
        }
        GameResult<MixResItem> consumeRes = new MixRes(row.composeCost1).consume(role);
        if (!consumeRes.ok()) {
            role.getGame().notice.tipResItem(role, consumeRes.data);
            return r.fail(consumeRes);
        }
        Fairy fairy = new Fairy(role, tid, 1);
        role.getBag().getFairy().addItem(fairy, null);
        RewardShow rewardShow = new RewardShow();
        rewardShow.addInsRwd(GDObj.Type.FAIRY, fairy.uid);
        role.getGame().notice.dialog(role, rewardShow);
        return r;
    }

    private Hero getHero(Role role, String heroUid){
        return role.getBag().hero.getItem(heroUid);
    }

    /** 获取灵器对象，有英雄id从英雄身上取，没有则从背包里取 */
    public Fairy getFairy(Role role, String fairyUid, String heroUid, byte pos) {
        if (StringUtils.isNotBlank(heroUid)) {
            Hero hero = getHero(role, heroUid);
            if(hero != null){
                Fairy fairy = hero.fairiesOn.fairyMap.get(pos);
                if (StringUtils.equals(fairyUid, fairy.uid)) {
                    return fairy;
                }
            }
        } else {
            return role.getBag().getFairy().getItem(fairyUid);
        }
        return null;
    }
}
